package ynu.lcy.service.impl;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ynu.lcy.dao.ICartDao;
import ynu.lcy.dao.ICartFoodItemDao;
import ynu.lcy.dao.IFoodDao;
import ynu.lcy.dto.cart.UpdateCartRequestDTO;
import ynu.lcy.elememicroserviceserviceclient.service.AuthFeignClient;
import ynu.lcy.elememicroserviceserviceclient.service.BusinessFeignClient;
import ynu.lcy.entity.Cart;
import ynu.lcy.entity.CartFoodItem;
import ynu.lcy.entity.Food;
import ynu.lcy.service.CartService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import static ynu.lcy.elememicroservicecommon.utils.TokenUtils.getToken;


@Service
@Slf4j
public class CartServiceImpl implements CartService {
    @Resource
    private ICartDao dao;
    @Resource
    private IFoodDao foodDao;
    @Resource
    private ICartFoodItemDao cartFoodItemDao;
    @Resource
    private AuthFeignClient authFeignClient;
    @Resource
    private BusinessFeignClient businessFeignClient;

    /**
     * 获取顾客在指定商家的购物车
     *
     * @param businessId 商家ID
     * @param request    请求
     * @return 购物车
     */
    public Cart getCart(Long businessId, HttpServletRequest request) {
        Long loginUser = authFeignClient.getLoginUser(getToken(request));
        return dao.findCartByBusinessIdAndUserId(businessId, loginUser);
    }

    /**
     * 获取顾客全部购物车
     *
     * @param request 请求
     * @return 购物车列表
     */
    public List<Cart> list(HttpServletRequest request) {
        Long loginUser = authFeignClient.getLoginUser(getToken(request));
        return dao.findAllByUserIdIs(loginUser);
    }

    @Override
    public Cart get(Long id) {
        return dao.getReferenceById(id);
    }

    /**
     * 更新购物车
     *
     * @param dto     更新购物车请求DTO
     * @param request 请求
     * @return 是否更新成功
     */
    public CartFoodItem update(UpdateCartRequestDTO dto, HttpServletRequest request) {
        try {
            Long loginUser = authFeignClient.getLoginUser(getToken(request));
            //判断用户是否存在购物车
            Cart cart = getCart(dto.getBusinessId(), request);
            CartFoodItem cartFoodItem = null;
            if (Objects.isNull(cart)) {
                //不存在，则新建购物车
                cart = new Cart();
                cart.setBusinessId(dto.getBusinessId());
                cart.setUserId(loginUser);
                cart.setTotalQuantity(dto.getChangeQuantity());
                cart.setCreateTime(new Date());
                //新建cart-item
                cartFoodItem = new CartFoodItem();
                cartFoodItem.setCart(cart);
                Food food = foodDao.getReferenceById(dto.getFoodId());
                cartFoodItem.setFood(food);
                cartFoodItem.setCreateTime(new Date());
                cartFoodItem.setQuantity(dto.getChangeQuantity());
            }else {
                //判断商品是否存在购物车内
                Food food = foodDao.getReferenceById(dto.getFoodId());
                cartFoodItem = cartFoodItemDao.findCartFoodItemByCartIdAndFood(cart.getId(), food);
                if (Objects.isNull(cartFoodItem)) {
                    //不存在则新建
                    cartFoodItem = new CartFoodItem();
                    cartFoodItem.setFood(food);
                    cartFoodItem.setQuantity(dto.getChangeQuantity());
                    cart.setTotalQuantity(cart.getTotalQuantity()+dto.getChangeQuantity());

                }else {
                    //原来的数量
                    int initQuantity = cartFoodItem.getQuantity();
                    //存在则修改数量
                    cartFoodItem.setQuantity(dto.getChangeQuantity());
                    //修改购物车总数量
                    cart.setTotalQuantity(cart.getTotalQuantity()-initQuantity+dto.getChangeQuantity());
                    cart.setUpdateTime(new Date());
                }
                cartFoodItem.setCart(cart);
                cartFoodItem.setCreateTime(new Date());
            }
            return cartFoodItemDao.save(cartFoodItem);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("购物车商品数量更新失败");
            return null;
        }
    }
}
